import { setState } from './index'
import { apiSearchRegion, apiGetWeather } from '@/api/region'

const state = {
  cities: [],
  currCity: {},
  cityLoading: false,
  cityList: [],
  listLoading: false
}

const mutations = {
  setState,

  clearCityList(state) {
    state.cityList = []
  },

  updateCurrCity(state, city) {
    state.currCity = city
  },

  deleteCity(state, city) {
    state.cities = state.cities.filter(v => v.adcode !== city.adcode)
  }
}

const actions = {
  async searchRegion({ commit }, keywords) {
    if (!keywords) {
      commit('setState', { cityList: [] })
      return
    }
    commit('setState', { listLoading: true })
    const res = await apiSearchRegion(keywords)
    if (res.districts && res.districts.some(v => v.level !== 'province')) {
      commit('setState', {
        cityList: res.districts
          .filter(v => v.level !== 'province')
          .map(v => ({ name: v.name, adcode: v.adcode })),
        listLoading: false
      })
    }
  },

  async addCity({ state, commit }, city) {
    // 合并城市和天气信息
    if (!state.cities.some(v => v.adcode === city.adcode)) {
      const res = await apiGetWeather({ adcode: city.adcode })
      if (res.lives.length) {
        const { temperature, weather } = res.lives[0]
        commit('setState', { cities: [...state.cities, { ...city, temperature, weather }] })
      }
    }
  },

  // 首次打开获取数据
  async initRegion({ commit }) {
    const city = { adcode: 110100, name: '北京市' }
    commit('setState', { cityLoading: true })
    const res = await apiGetWeather({ adcode: city.adcode })
    const { temperature, weather } = res.lives[0]
    commit('setState', {
      cities: [...state.cities, { ...city, temperature, weather }],
      currCity: { ...city, temperature, weather },
      cityLoading: false
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
